<?php
/**
 * Created by PhpStorm.
 * User: hui
 * Date: 2017/2/25
 * Time: 21:54
 */
namespace app\admin\behavior;

use think\Loader;
use traits\controller\Jump;

load_trait('controller/Jump');

class Auth
{
    //引入跳转特性
    use Jump;

    //request对象
    protected $request;

    //admin逻辑对象
    protected $admin;

    //配置项目
    protected $config = [

    ];

    //构造函数
    public function __construct()
    {
        //读取配置
        if ($auth = config('auth')){
            $this->config = array_merge($this->config,$auth);
        }
        //初始化request
        $this->request = request();

        $this->admin = Loader::model('admin','logic');
    }

    /**
     * by kuddy
     * 行为启动
     * @return bool
     */
    public function run()
    {
        //获取当前页面控制品器
        $controller = $this->request->controller();
        //判断路由例外规则
        if ('index' == strtolower($controller)){
            return true;
        }
        //判断登录状态
        if (!session('admin')){
            return false;
        }
        //获取权限列表
        $list = $this->getAuthList();
        //判断是否超级管理员
        if (isset($list['all'])){
            return true;
        }
        //获取当前请求action
        $action = $this->getActionId();
        //判断是否在权限列表
        if (isset($list[$action])){
            return true;
        }
        $this->error('您无权访问本功能');
        return false;
    }

    /**
     * by kuddy
     * 获得权限列表
     * @return mixed
     */
    protected function getAuthList()
    {
        return $this->admin->authList();
    }

    /**
     * by kuddy
     * 获得页面请求ID
     * @return mixed
     */
    protected function getActionId()
    {
        $action = $this->request->dispatch()['module'];
        return $this->admin->actionId($action)['module_id'];
    }
}